<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Infotech Ltd.
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: mslaria $ ($Date: 2007/07/11 13:08:20 $)
// $RCSfile: staff_filters.php,v $ : $Revision: 1.8 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

require_once ("./includes/functions_html.php");
$template->loadLanguageSection("staff_tickets");
$template->loadLanguageSection("tickets_auditlogs");
$template->loadLanguageSection("staff_ticketfilters");
$template->loadLanguageSection("staff_tsearch");
require_once ("./modules/tickets/functions_ticketsearch.php");
require_once ("./modules/tickets/functions_ticketsui.php");
require_once ("./modules/tickets/functions_ticketcore.php");
require_once ("./modules/tickets/functions_filters.php");

/**
* ###############################################
* FUNCTION DECLARATIONS
* ###############################################
*/

/**
* Callback for parsing Filters data
*/
function _ticketFilterFields($arg)
{
	global $_SWIFT;
	$record = &$arg[0];
	$fields = &$arg[1];

	if ($record["filtertype"] == SWIFTPUBLIC)
	{
		$record["filtertype"] =$_SWIFT["language"]["public"];
	} else {
		$record["filtertype"] =$_SWIFT["language"]["private"];
	}

	$record["title"] = '<table width="100%" border="0" cellspacing="0" cellpadding="1"><tr><td width="1"><img src="'. $_SWIFT["themepath"] .'icon_filteritem.gif" border="0" /></td><td><span class="smalltext">&nbsp;<a href="index.php?_m=tickets&_a=editfilter&ticketfilterid='. $record["ticketfilterid"] .'">'. $record["title"] .'</a></span></td></tr></table>';

	$record["options"] = '<a href="index.php?_m=tickets&_a=editfilter&ticketfilterid='. $record["ticketfilterid"] .'" title="'. $_SWIFT["language"]["edit"] .'"><img src="'. $_SWIFT["themepath"] .'icon_edit.gif" border="0">&nbsp;'. $_SWIFT["language"]["edit"] .'</a>&nbsp;&nbsp;&nbsp;&nbsp;<a onClick="javascript:doConfirm(\''. $_SWIFT["language"]["filterdelconfirmmsg"] .'\', \'index.php?_m=tickets&_a=managefilters&do=delete&ticketfilterid='. $record["ticketfilterid"] .'\');" href="#" title="'. $_SWIFT["language"]["delete"] .'"><img src="'. $_SWIFT["themepath"] .'icon_delete.gif" border="0">&nbsp;'. $_SWIFT["language"]["delete"] .'</a>&nbsp;';

	return $record;
}

/**
* Mass Action: Delete Ticket Filters
*/
function _maDeleteTicketFilters()
{
	global $dbCore, $_SWIFT;

	if (_is_array($_POST["itemid"]))
	{
		deleteTicketFilters($_POST["itemid"]);
	}
}




ob_start();
?>
<script type="text/javascript">
			var cruleindex = 1;
			function newFilterCriteria()
			{
				var rowElement = document.createElement("div");
				rowElement.id = "rulerow"+cruleindex;
				var rowMod = cruleindex%2;
				rowElement.className = "searchrule"+rowMod;
				var tparent = browserObject("ruleparent");
				if (!tparent)
				{
					return false;
				}

				tparent.appendChild(rowElement);
				updateRuleHTML(cruleindex, "subject", '', '');
				cruleindex++;
			}

			function newRuleCriteria(crulename, selectedop, dfieldvalue)
			{
				var rowElement = document.createElement("div");
				rowElement.id = "rulerow"+cruleindex;
				var rowMod = cruleindex%2;
				rowElement.className = "searchrule"+rowMod;
				var tparent = browserObject("ruleparent");
				if (!tparent)
				{
					return false;
				}

				tparent.appendChild(rowElement);
				updateRuleHTML(cruleindex, crulename, selectedop, dfieldvalue);
				cruleindex++;
			}

			function removeRuleRow(ruleindex)
			{
				var tparent = browserObject("ruleparent");
				if (!tparent)
				{
					return false;
				}

				var rowElement = browserObject("rulerow"+ruleindex);
				if (!rowElement)
				{
					return false;
				}

				tparent.removeChild(rowElement);
			}

			function updateRuleHTML(ruleindex, fieldtype, selectedop, dfieldvalue)
			{
				var returnResult;

				if (!selectedop)
				{
					var selectedop = '';
				}
				if (!dfieldvalue)
				{
					var dfieldvalue = '';
				}

				returnResult = '<table border="0" cellpadding="3" cellspacing="1" width="100%"><tr><td align="left" width="1"><a href="javascript:void(0);" onClick="javascript:removeRuleRow(\''+ruleindex+'\');"><img src="<?=$_SWIFT["themepath"]?>icon_deletesmall.gif" title="<?=$_SWIFT["language"]["deletecriteria"]?>" border="0" /></a></td><td align="left" width="1"><select name="searchrules['+ ruleindex +'][0]" class="swiftselect" onChange="javascript:updateRuleHTML(\''+ ruleindex +'\', this.options[this.selectedIndex].value);">';
				returnResult += '<optgroup label="<?=$_SWIFT["language"]["sticket"]?>">';
				returnResult += '<option value="subject"'+selectedStatus(fieldtype, "subject")+'><?=addslashes($_SWIFT["language"]["ssubject"])?></option>';
				returnResult += '<option value="fullname"'+selectedStatus(fieldtype, "fullname")+'><?=addslashes($_SWIFT["language"]["sfullname"])?></option>';
				returnResult += '<option value="email"'+selectedStatus(fieldtype, "email")+'><?=addslashes($_SWIFT["language"]["semail"])?></option>';
				returnResult += '<option value="groupname"'+selectedStatus(fieldtype, "groupname")+'><?=addslashes($_SWIFT["language"]["sgroupname"])?></option>';
				returnResult += '<option value="tgroupid"'+selectedStatus(fieldtype, "tgroupid")+'><?=addslashes($_SWIFT["language"]["stgroup"])?></option>';
				returnResult += '<option value="notes"'+selectedStatus(fieldtype, "notes")+'><?=addslashes($_SWIFT["language"]["snotes"])?></option>';
				returnResult += '<option value="usernotes"'+selectedStatus(fieldtype, "usernotes")+'><?=addslashes($_SWIFT["language"]["susernotes"])?></option>';
				returnResult += '<option value="departmentid"'+selectedStatus(fieldtype, "departmentid")+'><?=addslashes($_SWIFT["language"]["sdepartment"])?></option>';
				returnResult += '<option value="ticketstatusid"'+selectedStatus(fieldtype, "ticketstatusid")+'><?=addslashes($_SWIFT["language"]["sticketstatus"])?></option>';
				returnResult += '<option value="priorityid"'+selectedStatus(fieldtype, "priorityid")+'><?=addslashes($_SWIFT["language"]["spriority"])?></option>';
				returnResult += '<option value="ownerstaffid"'+selectedStatus(fieldtype, "ownerstaffid")+'><?=addslashes($_SWIFT["language"]["sowner"])?></option>';
				returnResult += '<option value="flagtype"'+selectedStatus(fieldtype, "flagtype")+'><?=addslashes($_SWIFT["language"]["sflagtype"])?></option>';
				returnResult += '<option value="slaplanid"'+selectedStatus(fieldtype, "slaplanid")+'><?=addslashes($_SWIFT["language"]["sslaplan"])?></option>';
				returnResult += '<option value="dateline"'+selectedStatus(fieldtype, "dateline")+'><?=addslashes($_SWIFT["language"]["screationdate"])?></option>';
				returnResult += '<option value="datelinerange"'+selectedStatus(fieldtype, "datelinerange")+'><?=addslashes($_SWIFT["language"]["fcreationdaterange"])?></option>';
				returnResult += '<option value="duetime"'+selectedStatus(fieldtype, "duetime")+'><?=addslashes($_SWIFT["language"]["sduetime"])?></option>';
				returnResult += '<option value="duetimerange"'+selectedStatus(fieldtype, "duetimerange")+'><?=addslashes($_SWIFT["language"]["fduetimerange"])?></option>';
				returnResult += '<option value="lastactivity"'+selectedStatus(fieldtype, "lastactivity")+'><?=addslashes($_SWIFT["language"]["slastactivity"])?></option>';
				returnResult += '<option value="lastactivityrange"'+selectedStatus(fieldtype, "lastactivityrange")+'><?=addslashes($_SWIFT["language"]["flastactivityrange"])?></option>';
				returnResult += '<option value="lastuserreplytime"'+selectedStatus(fieldtype, "lastuserreplytime")+'><?=addslashes($_SWIFT["language"]["slastuserreplytime"])?></option>';
				returnResult += '<option value="lastuserreplytimerange"'+selectedStatus(fieldtype, "lastuserreplytimerange")+'><?=addslashes($_SWIFT["language"]["slastuserreplytimerange"])?></option>';
				returnResult += '<option value="laststaffreplytime"'+selectedStatus(fieldtype, "laststaffreplytime")+'><?=addslashes($_SWIFT["language"]["slaststaffreplytime"])?></option>';
				returnResult += '<option value="laststaffreplytimerange"'+selectedStatus(fieldtype, "laststaffreplytimerange")+'><?=addslashes($_SWIFT["language"]["slaststaffreplytimerange"])?></option>';
				returnResult += '<option value="isphonecall"'+selectedStatus(fieldtype, "isphonecall")+'><?=addslashes($_SWIFT["language"]["sphoneticket"])?></option>';
				returnResult += '<option value="isescalated"'+selectedStatus(fieldtype, "isescalated")+'><?=addslashes($_SWIFT["language"]["sisescalated"])?></option>';
				returnResult += '<option value="escalatedon"'+selectedStatus(fieldtype, "escalatedon")+'><?=addslashes($_SWIFT["language"]["fescalatedon"])?></option>';
				returnResult += '<option value="escalatedonrange"'+selectedStatus(fieldtype, "escalatedonrange")+'><?=addslashes($_SWIFT["language"]["fescalatedonrange"])?></option>';
				returnResult += '<option value="hasattachments"'+selectedStatus(fieldtype, "hasattachments")+'><?=addslashes($_SWIFT["language"]["shasattachments"])?></option>';
				returnResult += '<option value="hasnotes"'+selectedStatus(fieldtype, "hasnotes")+'><?=addslashes($_SWIFT["language"]["shasnotes"])?></option>';
				returnResult += '<option value="isemailed"'+selectedStatus(fieldtype, "isemailed")+'><?=addslashes($_SWIFT["language"]["sisemailed"])?></option>';
				returnResult += '<option value="hasbilling"'+selectedStatus(fieldtype, "hasbilling")+'><?=addslashes($_SWIFT["language"]["shasbilling"])?></option>';
				returnResult += '</optgroup>';
				<?
				// First get the custom field groups
				//Mahesh Slaria: Staff & user ticket creation
				$_customfieldgroups = $customfieldgroupidlist = $_customfields = $customfieldidlist = array();
				$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."customfieldgroups` WHERE `grouptype` IN ('". CUSTOMFIELD_USERTICKET ."', '". CUSTOMFIELD_STAFFTICKET ."', '". CUSTOMFIELD_STAFFUSERTICKET ."') ORDER BY `displayorder` ASC;");
				while ($dbCore->nextRecord())
				{
					$customfieldgroupidlist[]= $dbCore->Record["customfieldgroupid"];
					$_customfieldgroups[$dbCore->Record["customfieldgroupid"]] = $dbCore->Record;
					$_customfieldgroups[$dbCore->Record["customfieldgroupid"]]["fields"] = array();
				}

				if (count($customfieldgroupidlist))
				{
					$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."customfields` WHERE `customfieldgroupid` IN (". buildIN($customfieldgroupidlist) .");");
					while ($dbCore->nextRecord())
					{
						$customfieldidlist[] = $dbCore->Record["customfieldid"];
						$_customfields[$dbCore->Record["customfieldid"]] = $dbCore->Record;
						$_customfieldgroups[$dbCore->Record["customfieldgroupid"]]["fields"][$dbCore->Record["customfieldid"]] = &$_customfields[$dbCore->Record["customfieldid"]];
					}
				}

				foreach ($_customfieldgroups as $key=>$val)
				{
					?>
					returnResult += '<optgroup label="<?=addslashes($val["title"])?>">';
					<?
					foreach ($val["fields"] as $fieldkey=>$fieldval)
					{
						?>
						returnResult += '<option value="cfield_<?=$fieldval["customfieldid"]?>"'+selectedStatus(fieldtype, "cfield_<?=$fieldval["customfieldid"]?>")+'><?=addslashes($fieldval["title"])?></option>';
						<?
					}
					?>
					returnResult += '</optgroup>';
					<?
				}
				?>
				returnResult += '</select>';

				returnResult += "</td>";

				if (fieldtype == "subject") {
					returnResult += getOperatorHTML(ruleindex, "string", selectedop)+getQueryHTML(ruleindex, "text", dfieldvalue);
				} else if (fieldtype == "contents") {
					returnResult += getOperatorHTML(ruleindex, "string", selectedop)+getQueryHTML(ruleindex, "text", dfieldvalue);
				} else if (fieldtype == "departmentid") {
					returnResult += getOperatorHTML(ruleindex, "bool", selectedop)+getQueryHTML(ruleindex, "departmentid", dfieldvalue);
				} else if (fieldtype == "ticketstatusid") {
					returnResult += getOperatorHTML(ruleindex, "bool", selectedop)+getQueryHTML(ruleindex, "ticketstatusid", dfieldvalue);
				} else if (fieldtype == "priorityid") {
					returnResult += getOperatorHTML(ruleindex, "bool", selectedop)+getQueryHTML(ruleindex, "priorityid", dfieldvalue);
				} else if (fieldtype == "tgroupid") {
					returnResult += getOperatorHTML(ruleindex, "bool", selectedop)+getQueryHTML(ruleindex, "tgroupid", dfieldvalue);
				} else if (fieldtype == "ownerstaffid") {
					returnResult += getOperatorHTML(ruleindex, "bool", selectedop)+getQueryHTML(ruleindex, "ownerstaffid", dfieldvalue);
				} else if (fieldtype == "flagtype") {
					returnResult += getOperatorHTML(ruleindex, "bool", selectedop)+getQueryHTML(ruleindex, "flagtype", dfieldvalue);
				} else if (fieldtype == "isphonecall") {
					returnResult += getOperatorHTML(ruleindex, "bool", selectedop)+getQueryHTML(ruleindex, "bool", dfieldvalue);
				} else if (fieldtype == "isescalated") {
					returnResult += getOperatorHTML(ruleindex, "bool", selectedop)+getQueryHTML(ruleindex, "bool", dfieldvalue);
				} else if (fieldtype == "hasattachments") {
					returnResult += getOperatorHTML(ruleindex, "bool", selectedop)+getQueryHTML(ruleindex, "bool", dfieldvalue);
				} else if (fieldtype == "hasnotes") {
					returnResult += getOperatorHTML(ruleindex, "bool", selectedop)+getQueryHTML(ruleindex, "bool", dfieldvalue);
				} else if (fieldtype == "notes" || fieldtype == "email" || fieldtype == "fullname" || fieldtype == "groupname") {
					returnResult += getOperatorHTML(ruleindex, "resstring", selectedop)+getQueryHTML(ruleindex, "text", dfieldvalue);
				} else if (fieldtype == "usernotes") {
					returnResult += getOperatorHTML(ruleindex, "resstring", selectedop)+getQueryHTML(ruleindex, "text", dfieldvalue);
				} else if (fieldtype == "duetime") {
					returnResult += getOperatorHTML(ruleindex, "cal", selectedop)+getQueryHTML(ruleindex, "cal", dfieldvalue);
				} else if (fieldtype == "lastactivity" || fieldtype == "lastuserreplytime" || fieldtype == "laststaffreplytime") {
					returnResult += getOperatorHTML(ruleindex, "cal", selectedop)+getQueryHTML(ruleindex, "cal", dfieldvalue);
				} else if (fieldtype == "dateline" || fieldtype == "escalatedon") {
					returnResult += getOperatorHTML(ruleindex, "cal", selectedop)+getQueryHTML(ruleindex, "cal", dfieldvalue);
				} else if (fieldtype == "slaplanid") {
					returnResult += getOperatorHTML(ruleindex, "bool", selectedop)+getQueryHTML(ruleindex, "slaplanid", dfieldvalue);
				} else if (fieldtype == "isemailed") {
					returnResult += getOperatorHTML(ruleindex, "bool", selectedop)+getQueryHTML(ruleindex, "bool", dfieldvalue);
				} else if (fieldtype == "hasbilling") {
					returnResult += getOperatorHTML(ruleindex, "bool", selectedop)+getQueryHTML(ruleindex, "bool", dfieldvalue);
				} else if (fieldtype == "datelinerange" || fieldtype == "lastactivityrange" || fieldtype == "duetimerange" || fieldtype == "escalatedonrange" || fieldtype == "lastuserreplytimerange" || fieldtype == "laststaffreplytimerange") {
					returnResult += getOperatorHTML(ruleindex, "calrange", selectedop)+getQueryHTML(ruleindex, "calrange", dfieldvalue);
				}

				var cfield = fieldtype.substring(0,7);
				if (cfield == "cfield_")
				{
					returnResult += getOperatorHTML(ruleindex, "resstring", selectedop)+getQueryHTML(ruleindex, "text", dfieldvalue);
				}

				var dRow = browserObject("rulerow"+ruleindex);
				if (!dRow)
				{
					return;
				}

				dRow.innerHTML = returnResult+'</tr></table>';
			}

			function selectedStatus(fieldtype, fieldvalue)
			{
				if (fieldtype == fieldvalue)
				{
					return " selected";
				}
			}

			function getOperatorHTML(ruleindex, optype, selectedop)
			{
				if (!ruleindex)
				{
					return;
				}

				if (optype == "string")
				{
					if (!selectedop)
					{
						var selectedop = '<?=OP_CONTAINS?>';
					}
					return '<td align="left" width="1"><select name="searchrules['+ ruleindex +'][1]" class="swiftselect"><option value="<?=OP_CONTAINS?>"'+selectedStatus(selectedop, "<?=OP_CONTAINS?>")+'><?=$_SWIFT["language"]["opcontains"]?></option><option value="<?=OP_NOTCONTAINS?>"'+selectedStatus(selectedop, "<?=OP_NOTCONTAINS?>")+'><?=addslashes($_SWIFT["language"]["opnotcontains"])?></option><option value="<?=OP_EQUAL?>"'+selectedStatus(selectedop, "<?=OP_EQUAL?>")+'><?=$_SWIFT["language"]["opequal"]?></option><option value="<?=OP_NOTEQUAL?>"'+selectedStatus(selectedop, "<?=OP_NOTEQUAL?>")+'><?=$_SWIFT["language"]["opnotequal"]?></option></select></td>';
				} else if (optype == "resstring") {
					return '<td align="left" width="1"><select name="searchrules['+ ruleindex +'][1]" class="swiftselect"><option value="<?=OP_CONTAINS?>" selected><?=$_SWIFT["language"]["opcontains"]?></option></select></td>';
				} else if (optype == "bool") {
					if (!selectedop)
					{
						var selectedop = '<?=OP_EQUAL?>';
					}
					return '<td align="left" width="1"><select name="searchrules['+ ruleindex +'][1]" class="swiftselect"><option value="<?=OP_EQUAL?>"'+selectedStatus(selectedop, "<?=OP_EQUAL?>")+'><?=$_SWIFT["language"]["opequal"]?></option><option value="<?=OP_NOTEQUAL?>"'+selectedStatus(selectedop, "<?=OP_NOTEQUAL?>")+'><?=$_SWIFT["language"]["opnotequal"]?></option></select></td>';
				} else if (optype == "int") {
					if (!selectedop)
					{
						var selectedop = '<?=OP_EQUAL?>';
					}
					return '<td align="left" width="1"><select name="searchrules['+ ruleindex +'][1]" class="swiftselect"><option value="<?=OP_GREATER?>"'+selectedStatus(selectedop, "<?=OP_GREATER?>")+'><?=$_SWIFT["language"]["opgreater"]?></option><option value="<?=OP_LESS?>"'+selectedStatus(selectedop, "<?=OP_LESS?>")+'><?=$_SWIFT["language"]["opless"]?></option><option value="<?=OP_EQUAL?>"'+selectedStatus(selectedop, "<?=OP_EQUAL?>")+'><?=$_SWIFT["language"]["opequal"]?></option><option value="<?=OP_NOTEQUAL?>"'+selectedStatus(selectedop, "<?=OP_NOTEQUAL?>")+'><?=$_SWIFT["language"]["opnotequal"]?></option></select></td>';
				} else if (optype == "cal") {
					if (!selectedop)
					{
						var selectedop = '<?=OP_GREATER?>';
					}
					return '<td align="left" width="1"><select name="searchrules['+ ruleindex +'][1]" class="swiftselect"><option value="<?=OP_GREATER?>"'+selectedStatus(selectedop, "<?=OP_GREATER?>")+'><?=$_SWIFT["language"]["opgreater"]?></option><option value="<?=OP_LESS?>"'+selectedStatus(selectedop, "<?=OP_LESS?>")+'><?=$_SWIFT["language"]["opless"]?></option></select></td>';
				} else if (optype == "calrange") {
					return '<td align="left" width="1"><select name="searchrules['+ ruleindex +'][1]" class="swiftselect"><option value="<?=OP_EQUAL?>" selected><?=$_SWIFT["language"]["opequal"]?></option></select></td>';
				}
			}

			function getQueryHTML(ruleindex, querytype, dfieldvalue)
			{
				if (!ruleindex)
				{
					return;
				}

				var returnResult = '<td align="left">';
				if (querytype == "text")
				{
					returnResult += '<input type="text" size="20" class="swifttext" name="searchrules['+ ruleindex +'][2]" style="width:98%;" value="'+ dfieldvalue +'" />';
				} else if (querytype == "textentire") {
					returnResult += '<input type="text" size="20" class="swifttext" name="searchrules['+ ruleindex +'][2]" style="width:50%;" value="'+ dfieldvalue +'" /><span class="smalltext">&nbsp;&nbsp;<?=addslashes($_SWIFT["language"]["squerydesc"])?></span>';
				} else if (querytype == "ticketstatusid") {
					returnResult += '<select name="searchrules['+ ruleindex +'][2]" class="swiftselect">';
					<?
					foreach ($_SWIFT["statuscache"] as $key=>$val)
					{
						?>returnResult += '<option value="<?=$val["ticketstatusid"]?>" style="color:<?=$val["statuscolor"]?>;"'+ selectedStatus(dfieldvalue, '<?=$val["ticketstatusid"]?>') +'><?=addslashes($val["title"])?></option>';<?
					}
					?>
					returnResult += '</select>';
				} else if (querytype == "tgroupid") {
					returnResult += '<select name="searchrules['+ ruleindex +'][2]" class="swiftselect">';
					<?
					foreach ($_SWIFT["tgroupcache"] as $key=>$val)
					{
						?>returnResult += '<option value="<?=$val["tgroupid"]?>"'+ selectedStatus(dfieldvalue, '<?=$val["tgroupid"]?>') +'><?=addslashes($val["title"])?></option>';<?
					}
					?>
					returnResult += '</select>';
				} else if (querytype == "priorityid") {
					returnResult += '<select name="searchrules['+ ruleindex +'][2]" class="swiftselect">';
					<?
					foreach ($_SWIFT["prioritycache"] as $key=>$val)
					{
						?>returnResult += '<option value="<?=$val["priorityid"]?>" style="color:<?=$val["frcolorcode"]?>;background:<?=$val["bgcolorcode"]?>;"'+ selectedStatus(dfieldvalue, '<?=$val["priorityid"]?>') +'><?=addslashes($val["title"])?></option>';<?
					}
					?>
					returnResult += '</select>';
				} else if (querytype == "ownerstaffid") {
					returnResult += '<select name="searchrules['+ ruleindex +'][2]" class="swiftselect">';
					<?
					foreach ($_SWIFT["staffcache"] as $key=>$val)
					{
						?>returnResult += '<option value="<?=$val["staffid"]?>"'+ selectedStatus(dfieldvalue, '<?=$val["staffid"]?>') +'><?=addslashes($val["fullname"])?></option>';<?
					}
					?>
					returnResult += '</select>';
				} else if (querytype == "departmentid") {
					returnResult += '<select name="searchrules['+ ruleindex +'][2]" class="swiftselect">';
					<?
					$_assigns = getAssignedDepartments(MODULE_TICKETS);
					foreach ($_assigns as $key=>$val)
					{
						$_department = $_SWIFT["departmentcache"][$val];
						?>returnResult += '<option value="<?=$_department["departmentid"]?>"'+ selectedStatus(dfieldvalue, '<?=$_department["departmentid"]?>') +'><?=addslashes($_department["title"])?></option>';<?
					}
					?>
					returnResult += '</select>';
				} else if (querytype == "slaplanid") {
					returnResult += '<select name="searchrules['+ ruleindex +'][2]" class="swiftselect">';
					<?
					if (_is_array($_SWIFT["slaplancache"]))
					{
						foreach ($_SWIFT["slaplancache"] as $key=>$val)
						{
							?>returnResult += '<option value="<?=$val["slaplanid"]?>"'+ selectedStatus(dfieldvalue, '<?=$val["slaplanid"]?>') +'><?=addslashes($val["title"])?></option>';<?
						}
					}
					?>
					returnResult += '</select>';
				} else if (querytype == "cal") {
					returnResult += '<input type="text" name="searchrules['+ruleindex+'][2]" id="rulecal'+ ruleindex +'" onclick="return showCalendar(\'rulecal'+ ruleindex +'\', \'<?=iif($_SWIFT["settings"]["dt_caltype"]=="us", "%m/%d/%Y", "%d/%m/%Y")?>\');" size="12" readonly="1" value="'+ dfieldvalue +'" class="swifttext"/>&nbsp;<img src="<?=$_SWIFT["themepath"]?>calendar.gif" onclick="return showCalendar(\'rulecal'+ ruleindex +'\', \'<?=iif($_SWIFT["settings"]["dt_caltype"]=="us", "%m/%d/%Y", "%d/%m/%Y")?>\');" style="cursor: pointer;" align="absmiddle"/>';
				} else if (querytype == "calrange") {
					returnResult += '<select name="searchrules['+ ruleindex +'][2]" class="swiftselect">';
					returnResult += '<option value="today"'+ selectedStatus(dfieldvalue, 'today') +'><?=addslashes($_SWIFT["language"]["ftoday"])?></option>';
					returnResult += '<option value="yesterday"'+ selectedStatus(dfieldvalue, 'yesterday') +'><?=addslashes($_SWIFT["language"]["fyesterday"])?></option>';
					returnResult += '<option value="thisweek"'+ selectedStatus(dfieldvalue, 'thisweek') +'><?=addslashes($_SWIFT["language"]["fthisweek"])?></option>';
					returnResult += '<option value="lastweek"'+ selectedStatus(dfieldvalue, 'lastweek') +'><?=addslashes($_SWIFT["language"]["flastweek"])?></option>';
					returnResult += '<option value="thismonth"'+ selectedStatus(dfieldvalue, 'thismonth') +'><?=addslashes($_SWIFT["language"]["fthismonth"])?></option>';
					returnResult += '<option value="lastmonth"'+ selectedStatus(dfieldvalue, 'lastmonth') +'><?=addslashes($_SWIFT["language"]["flastmonth"])?></option>';
					returnResult += '<option value="lastthreemonths"'+ selectedStatus(dfieldvalue, 'lastthreemonths') +'><?=addslashes($_SWIFT["language"]["flastthreemonths"])?></option>';
					returnResult += '<option value="lastsixmonths"'+ selectedStatus(dfieldvalue, 'lastsixmonths') +'><?=addslashes($_SWIFT["language"]["flastsixmonths"])?></option>';
					returnResult += '<option value="thisyear"'+ selectedStatus(dfieldvalue, 'thisyear') +'><?=addslashes($_SWIFT["language"]["fthisyear"])?></option>';
					returnResult += '<option value="lastyear"'+ selectedStatus(dfieldvalue, 'lastyear') +'><?=addslashes($_SWIFT["language"]["flastyear"])?></option>';
					returnResult += '</select>';
				} else if (querytype == "bool") {
					returnResult += '<select name="searchrules['+ ruleindex +'][2]" class="swiftselect"><option value="1"'+ selectedStatus(dfieldvalue, '1') +'><?=$_SWIFT["language"]["strue"]?></option><option value="0"'+ selectedStatus(dfieldvalue, '0') +'><?=$_SWIFT["language"]["sfalse"]?></option></select>';
				} else if (querytype == "flagtype") {
					<?
					$flagbgcolors = array(FLAG_PURPLE => "#A5587C", FLAG_ORANGE => "#FF8C5A", FLAG_GREEN => "#8BB467", FLAG_YELLOW => "#FFC160", FLAG_RED => "#CF5D60", FLAG_BLUE => "#5C83B4");
					?>
					returnResult += '<select name="searchrules['+ ruleindex +'][2]" class="swiftselect">';
					returnResult += '<option value="<?=FLAG_PURPLE?>" style="background: <?=$flagbgcolors[FLAG_PURPLE]?>; color: #FFFFFF;"'+ selectedStatus(dfieldvalue, '<?=FLAG_PURPLE?>') +'><?=addslashes($_SWIFT["language"]["purpleflag"])?></option>';
					returnResult += '<option value="<?=FLAG_RED?>" style="background: <?=$flagbgcolors[FLAG_RED]?>; color: #FFFFFF;"'+ selectedStatus(dfieldvalue, '<?=FLAG_RED?>') +'><?=addslashes($_SWIFT["language"]["redflag"])?></option>';
					returnResult += '<option value="<?=FLAG_ORANGE?>" style="background: <?=$flagbgcolors[FLAG_ORANGE]?>; color: #FFFFFF;"'+ selectedStatus(dfieldvalue, '<?=FLAG_ORANGE?>') +'><?=addslashes($_SWIFT["language"]["orangeflag"])?></option>';
					returnResult += '<option value="<?=FLAG_YELLOW?>" style="background: <?=$flagbgcolors[FLAG_YELLOW]?>; color: #FFFFFF;"'+ selectedStatus(dfieldvalue, '<?=FLAG_YELLOW?>') +'><?=addslashes($_SWIFT["language"]["yellowflag"])?></option>';
					returnResult += '<option value="<?=FLAG_BLUE?>" style="background: <?=$flagbgcolors[FLAG_BLUE]?>; color: #FFFFFF;"'+ selectedStatus(dfieldvalue, '<?=FLAG_BLUE?>') +'><?=addslashes($_SWIFT["language"]["blueflag"])?></option>';
					returnResult += '<option value="<?=FLAG_GREEN?>" style="background: <?=$flagbgcolors[FLAG_GREEN]?>; color: #FFFFFF;"'+ selectedStatus(dfieldvalue, '<?=FLAG_GREEN?>') +'><?=addslashes($_SWIFT["language"]["greenflag"])?></option>';
					returnResult += '<option value="0" style="background: #CCCCCC; color: #FFFFFF;"'+ selectedStatus(dfieldvalue, '0') +'><?=addslashes($_SWIFT["language"]["noflag"])?></option>';
					returnResult += '</select>';
				}

				return returnResult+'</td>';
			}
</script>
<?
$jscode = ob_get_contents();
ob_end_clean();

/**
* ###############################################
* RUN EXISTING FILTER
* ###############################################
*/
if ($eventaction == "runfilter")
{
	$_ticketfilter = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."ticketfilters` WHERE `ticketfilterid` = '". intval($_REQUEST["ticketfilterid"]) ."';");
	if (empty($_ticketfilter["ticketfilterid"]) || ($_ticketfilter["filtertype"] == SWIFTPRIVATE && $_ticketfilter["staffid"] != $_SWIFT["staff"]["staffid"]))
	{
		trigger_error($_SWIFT["language"]["invalidfilteraccess"], E_USER_ERROR);
		exit;
	}

	$_filterrules = array();
	$index = 0;
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."ticketfilterfields` WHERE `ticketfilterid` = '". intval($_ticketfilter["ticketfilterid"]) ."';");
	while ($dbCore->nextRecord())
	{
		$_filterrules[$index][0] = $dbCore->Record["fieldtitle"];
		$_filterrules[$index][1] = $dbCore->Record["fieldoper"];
		$_filterrules[$index][2] = $dbCore->Record["fieldvalue"];
		$index++;
	}

	$_ticketsearchid = processSearchRules($_filterrules, $_ticketfilter["filteroptions"], $_ticketfilter["ticketfilterid"]);
	if ($_ticketsearchid)
	{
		header("location: index.php?_m=tickets&_a=manage&ticketsearchid=".intval($_ticketsearchid));
		exit;
	} else {
		// Search Failed
		header("location: index.php?_m=tickets&_a=manage&fnomatch=1");
		exit;
	}



/**
* ###############################################
* INSERT NEW FILTER
* ###############################################
*/
} else if ($eventaction == "insertfilter") {
	if ($_POST["step"] == "1")
	{
		if (trim($_POST["title"]) == "" || trim($_POST["filtertype"]) == "" || !count($_POST["searchrules"]))
		{
			$errormessage = $_SWIFT["language"]["requiredfieldempty"];
		} else {
			$_ticketfilterid = insertTicketFilter($_POST["title"], $_POST["filtertype"], $_POST["searchrules"], $_POST["ruleoptions"]);

			printRedirect(sprintf($_SWIFT["language"]["filterinsertconfirm"], htmlspecialchars($_POST["title"])), "index.php?_m=tickets&_a=managefilters&insertfilter=".urlencode($_POST["title"]));
			exit;
		}
	}

	renderTicketTree();

	$template->assign("calendar", true);

	$interface->staffHeader($_SWIFT["language"]["ticket"] ." &gt; ".$_SWIFT["language"]["insertfilter"], 2);

	$interface->staffNavBar('<a href="index.php?_m=tickets&_a=manage" title="'.$_SWIFT["language"]["tickets"].'">'.$_SWIFT["language"]["tickets"].'</a> &raquo; <a href="index.php?_m=tickets&_a=insertfilter" title="'.$_SWIFT["language"]["insertfilter"].'">'.$_SWIFT["language"]["insertfilter"]."</a>", $_SWIFT["language"]["insertfilterdesc"], 2);

	echo $jscode;

	printInfoBox($infomessage);
	printErrorBox($errormessage);

	printFormStart();
	printMainTableHeader($_SWIFT["language"]["insertfilter"]);

	printTextRow("title", $_SWIFT["language"]["filtertitle"], $_SWIFT["language"]["desc_filtertitle"], "text", $_POST["title"]);

	printPublicPrivateRow("filtertype", $_SWIFT["language"]["filtertype"], $_SWIFT["language"]["desc_filtertype"], SWIFTPUBLIC);

	printDescRow($_SWIFT["language"]["filtercriteria"]);
	echo '<tr class="'. getRowBG() .'">
	<td align="left" colspan="2"><span class="smalltext"><div id="ruleparent"></div></span></td></tr>';

	echo '<tr class="'. getRowBG() .'">
	<td align="left" colspan="2"><span class="smalltext"><a href="javascript:newFilterCriteria();"><img src="'. $_SWIFT["themepath"] .'icon_add.gif" border="0" align="absmiddle" />&nbsp;'. $_SWIFT["language"]["newcriteria"] .'</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<label for="ruleall"><input type="radio" name="ruleoptions" value="all" id="ruleall" checked>'. $_SWIFT["language"]["fmatchall"] .'</label>&nbsp;<label for="ruleany"><input type="radio" name="ruleoptions" value="any" id="ruleany">'. $_SWIFT["language"]["fmatchany"] .'</label></span></td></tr>';

	printSubmitRow($_SWIFT["language"]["insert"]);

	printMainTableFooter();

	addHiddenField("_m", "tickets");
	addHiddenField("_a", "insertfilter");
	addHiddenField("step", "1");
	printFormEnd();


	?>
	<script type="text/javascript">
		newFilterCriteria();
	</script>
	<?
	$template->assign("backurl", "index.php?_m=tickets&_a=manage");
	$interface->staffFooter();





/**
* ###############################################
* EDIT EXISTING FILTER
* ###############################################
*/
} else if ($eventaction == "editfilter") {
	$_ticketfilter = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."ticketfilters` WHERE `ticketfilterid` = '". intval($_REQUEST["ticketfilterid"]) ."';");
	if (empty($_ticketfilter["ticketfilterid"]) || ($_ticketfilter["filtertype"] == SWIFTPRIVATE && $_ticketfilter["staffid"] != $_SWIFT["staff"]["staffid"]))
	{
		trigger_error($_SWIFT["language"]["invalidfilteraccess"], E_USER_ERROR);
		exit;
	}

	$_ticketfilterfields = array();
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."ticketfilterfields` WHERE `ticketfilterid` = '". intval($_ticketfilter["ticketfilterid"]) ."';");
	while ($dbCore->nextRecord())
	{
		$_ticketfilterfields[$dbCore->Record["ticketfilterfieldid"]] = $dbCore->Record;
	}

	if ($_POST["step"] == "1")
	{
		if (trim($_POST["title"]) == "" || trim($_POST["filtertype"]) == "" || !count($_POST["searchrules"]))
		{
			$errormessage = $_SWIFT["language"]["requiredfieldempty"];
		} else {
			updateTicketFilter($_ticketfilter["ticketfilterid"], $_POST["title"], $_POST["filtertype"], $_POST["searchrules"], $_POST["ruleoptions"]);

			printRedirect(sprintf($_SWIFT["language"]["filtereditconfirm"], htmlspecialchars($_POST["title"])), "index.php?_m=tickets&_a=managefilters&editfilter=".urlencode($_POST["title"]));
			exit;
		}
	}

	renderTicketTree();

	$template->assign("calendar", true);

	$interface->staffHeader($_SWIFT["language"]["ticket"] ." &gt; ".$_SWIFT["language"]["editfilter"], 2);

	$interface->staffNavBar('<a href="index.php?_m=tickets&_a=manage" title="'.$_SWIFT["language"]["tickets"].'">'.$_SWIFT["language"]["tickets"].'</a> &raquo; <a href="index.php?_m=tickets&_a=editfilter&ticketfilterid='. intval($_ticketfilter["ticketfilterid"]) .'" title="'.$_SWIFT["language"]["editfilter"].'">'.$_SWIFT["language"]["editfilter"]."</a>", $_SWIFT["language"]["editfilterdesc"], 2);

	echo $jscode;

	printInfoBox($infomessage);
	printErrorBox($errormessage);

	printFormStart();
	printMainTableHeader($_SWIFT["language"]["editfilter"]);

	printTextRow("title", $_SWIFT["language"]["filtertitle"], $_SWIFT["language"]["desc_filtertitle"], "text", $_ticketfilter["title"]);

	printPublicPrivateRow("filtertype", $_SWIFT["language"]["filtertype"], $_SWIFT["language"]["desc_filtertype"], iif($_ticketfilter["filtertype"]==SWIFTPUBLIC, true, false));

	printDescRow($_SWIFT["language"]["filtercriteria"]);
	echo '<tr class="'. getRowBG() .'">
	<td align="left" colspan="2"><span class="smalltext"><div id="ruleparent"></div></span></td></tr>';

	echo '<tr class="'. getRowBG() .'">
	<td align="left" colspan="2"><span class="smalltext"><a href="javascript:newFilterCriteria();"><img src="'. $_SWIFT["themepath"] .'icon_add.gif" border="0" align="absmiddle" />&nbsp;'. $_SWIFT["language"]["newcriteria"] .'</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<label for="ruleall"><input type="radio" name="ruleoptions" value="all" id="ruleall"'. iif($_ticketfilter["filteroptions"]=="all", " checked") .'>'. $_SWIFT["language"]["fmatchall"] .'</label>&nbsp;<label for="ruleany"><input type="radio" name="ruleoptions" value="any" id="ruleany"'. iif($_ticketfilter["filteroptions"]=="any", " checked") .'>'. $_SWIFT["language"]["fmatchany"] .'</label></span></td></tr>';

	printSubmitRow($_SWIFT["language"]["insert"]);

	printMainTableFooter();

	addHiddenField("_m", "tickets");
	addHiddenField("_a", "editfilter");
	addHiddenField("ticketfilterid", $_ticketfilter["ticketfilterid"]);
	addHiddenField("step", "1");
	printFormEnd();


	?>
	<script type="text/javascript">
		<?=criteriaArrayToForm($_ticketfilterfields)?>
	</script>
	<?
	$template->assign("backurl", "index.php?_m=tickets&_a=manage");
	$interface->staffFooter();





/**
* ###############################################
* MANAGE EXISTING FILTERS
* ###############################################
*/
} else if ($eventaction == "managefilters") {
	if ($_GET["do"] == "delete" && !empty($_GET["ticketfilterid"]))
	{
		deleteTicketFilters(array($_GET["ticketfilterid"]));

		printRedirect($_SWIFT["language"]["filterdelconfirm"], "index.php?_m=tickets&_a=managefilters&filterdel=1");
		exit;
	}

	if (!empty($_GET["insertfilter"]))
	{
		$infomessage = sprintf($_SWIFT["language"]["filterinsertconfirm"], htmlspecialchars($_GET["insertfilter"]));
	} else if (!empty($_GET["editfilter"])) {
		$infomessage = sprintf($_SWIFT["language"]["filtereditconfirm"], htmlspecialchars($_GET["editfilter"]));
	} else if (!empty($_GET["filterdel"])) {
		$infomessage = $_SWIFT["language"]["filterdelconfirm"];
	}
	

	$options["recordsperpage"] = "10";
	$options["sortby"] = "title";
	$options["sortorder"] = "asc";
	$options["massaction"][0]["title"] = $_SWIFT["language"]["delete"];
	$options["massaction"][0]["callback"] = "_maDeleteTicketFilters";

	$options["idname"] = "ticketfilterid";
	$options["quicksearch"] = true;

	$options["advancedsearch"][0]["title"] = $_SWIFT["language"]["title"];
	$options["advancedsearch"][0]["query"] = 'SELECT * FROM `'. TABLE_PREFIX .'ticketfilters` WHERE `title` LIKE \'%$_searchstr%\' AND ((`filtertype` = \''. ALERT_PUBLIC .'\') OR (`filtertype` = \''. ALERT_PRIVATE .'\' AND `staffid` = \''. intval($_SWIFT["staff"]["staffid"]) .'\')) $_sortjoin;';

	$options["callback"] = "_ticketFilterFields";

	$fields[0]["name"] = "title";
	$fields[0]["title"] = $_SWIFT["language"]["filtertitle"];
	$fields[0]["width"] = "";

	$fields[1]["name"] = "filtertype";
	$fields[1]["title"] = $_SWIFT["language"]["filtertype"];
	$fields[1]["width"] = "150";
	$fields[1]["align"] = "center";

	$fields[2]["type"] = "custom";
	$fields[2]["name"] = "options";
	$fields[2]["title"] = $_SWIFT["language"]["options"];
	$fields[2]["width"] = "150";
	$fields[2]["align"] = "center";

	$grid = new Grid();

	renderTicketTree();
	$interface->staffHeader($_SWIFT["language"]["tickets"]." &gt; ".$_SWIFT["language"]["managefilters"], 2);

	$interface->staffNavBar('<a href="index.php?_m=tickets&_a=manage" title="'.$_SWIFT["language"]["tickets"].'">'.$_SWIFT["language"]["tickets"].'</a> &raquo; <a href="index.php?_m=tickets&_a=managefilters" title="'.$_SWIFT["language"]["managefilters"].'">'.$_SWIFT["language"]["managefilters"].'</a>', "", 2);

	$grid->start("ticketfilters", $_SWIFT["language"]["filterlist"], 'SELECT * FROM `'. TABLE_PREFIX .'ticketfilters` WHERE (`filtertype` = \''. SWIFTPUBLIC .'\') OR (`filtertype` = \''. SWIFTPRIVATE .'\' AND `staffid` = \''. intval($_SWIFT["staff"]["staffid"]) .'\') $_sortjoin;', 'SELECT COUNT(*) AS totalitems FROM `'. TABLE_PREFIX .'ticketfilters` AS ticketfilters WHERE (`filtertype` = \''. SWIFTPUBLIC .'\') OR (`filtertype` = \''. SWIFTPRIVATE .'\' AND `staffid` = \''. intval($_SWIFT["staff"]["staffid"]) .'\');', 'SELECT * FROM `'. TABLE_PREFIX .'ticketfilters` WHERE `title` LIKE \'%$_searchstr%\' AND ((`filtertype` = \''. SWIFTPUBLIC .'\') OR (`filtertype` = \''. SWIFTPRIVATE .'\' AND `staffid` = \''. intval($_SWIFT["staff"]["staffid"]) .'\')) $_sortjoin;', $fields, $options);

	printInfoBox($infomessage);
	printErrorBox($errormessage);

	$grid->display("ticketfilters");

	$interface->staffFooter();
}

?>